<template>
	<div class="user box" id="rightCont">
		<div class="title">
			<span>{{ nameTitle }}</span>
		</div>
		<div class="main">
			<div class="main-left">
				<div class="search">
					<el-autocomplete :fetch-suggestions="querySearch" placeholder="请输入部门名称" :trigger-on-focus="false" size="mini"
					@select="handleSelect" v-model="searchTreeValue">
					<i slot="prefix" class="el-input__icon el-icon-Ssearch"></i>
					</el-autocomplete>
				</div>
				<div class="tree">
					<el-tree
					:data="elTree" 
					:props="defaultProps"
					node-key="label"
					:default-expanded-keys="['宜宾九阵软件科技有限公司']"
					accordion
					ref="tree"
					:filter-node-method="filterNode"
					@node-click="handleNodeClick"
					class="custom-tree"
					element-loading-spinner="el-icon-more-outline"
					>
					<span class="custom-tree-node" slot-scope="{ node, data }" style="font-size: 12px;">
						<span :name="node.label">
							<i v-if="!data.children"
							:class="node.expanded ? 'el-icon-bumenOpen' : 'el-icon-bumenClose'"></i>
							<i v-else class="el-icon-bumenOpen"></i>
							<span style="margin-left: 8px;">{{ node.label }}</span>
						</span>
					</span>
					</el-tree>
				</div>
			</div>
			<div class="main-right" ref="mainRight">
				<div class="searchValue">
					<el-autocomplete :fetch-suggestions="querySearch" placeholder="请输入用户名称" :trigger-on-focus="false" size="mini"
						@select="handleSelect" v-model="searchValue">
					<i slot="prefix" class="el-input__icon el-icon-Ssearch"></i>
					</el-autocomplete>
					<el-select v-model="selectValue" placeholder="请选择状态" size="mini" @change="ChangeStatus">
					    <el-option
					      v-for="item in options"
					      :key="item.value"
					      :label="item.label"
					      :value="item.value">
					    </el-option>
					</el-select>
					<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
				</div>
				<!-- btn3 -->
				<div class="btnBottom">
					<!-- feet -->
					<div class="feet" id="feet">
						<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="feetHandClick(v,i)">{{ v.title }}</el-button>
					</div>
					<div class="b">
						<el-button v-for="(v,i) in headerBtnbottomRight" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="headerBtnbottomRightClick(i)">
							<span v-if="v.title">{{ v.title }}</span>
						</el-button>
					</div>
				</div>
				<div class="content">
					<el-table :data="tableData" :header-cell-style="{ background: '#f4f4f4 !important'}" border 
					highlight-current-row @current-change="handleCurrentTableChange"
					@row-dblclick="handledbRow" :style="{ width: windowWidth + 'px' }" v-loading="loading" element-loading-spinner="el-icon-more-outline">
						<el-table-column v-for="(col, inx) in tableRows" :key="inx" border='false' :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
						<!-- fixed -->
						<el-table-column fixed="left" label="序号" type="index"></el-table-column>
						<el-table-column prop="status" label="状态" width="120" align="center">
						  <template slot-scope="{ row }">
						    <el-button 
							  :loading="loading"
						      size="mini" 
							  plain
						      :type="row.status === '1' ? 'danger' : 'success'" 
						      @click="toggleStatus(row)"
						    >
						      {{ row.status === '1' ? '去禁用' : '去启用' }}
						    </el-button>
						  </template>
						</el-table-column>
						<!-- edit -->
						<el-table-column fixed="right" label="操作" width="148">
						    <template slot-scope="scope">
							  <div class="editbox" style="display: flex;justify-content: center;align-items: ;">
								<el-link style="font-size:12px;" type="primary" @click="handleClickEdit(scope.row)" size="mini">修改</el-link>
								<!-- <el-link style="margin-left:12px;font-size:12px;" type="danger" @click="handleDelete(scope.row.id)" size="mini">删除</el-link> -->
								<el-dropdown style="margin-left:12px;" @command="HandleCommand(scope.row)">
								 <span style="color: #409EFF">更多<i class="el-icon-down"></i></span>
								  <el-dropdown-menu slot="dropdown">
								    <el-dropdown-item command="editPwd"><i class="el-icon-key"></i>重置密码</el-dropdown-item>
								  </el-dropdown-menu>
								</el-dropdown>
							  </div>
						    </template>
						</el-table-column>
					</el-table>
					
				</div>
				<!-- 分页 -->
				<el-pagination
				style="margin: 12px;"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="pageNum"
				:page-sizes="[15, 50, 100]"
				:page-size="pageSize"
				:total="totalSize"
				layout="total, sizes, prev, pager, next, jumper"
				background
				>
				</el-pagination>
			</div>
		</div>
		<!-- 新增Model -->
		<div class="addModel">
			<el-dialog
			  title="新增系统用户"
			  :visible.sync="addModelDialogVisible"
			  width="48%"
			  :before-close="handleClose">
			  <!-- 新增主体 -->
			  <div class="content">
			  	<el-form ref="addForm" :model="addForm" :rules="rules" label-width="88px" size="mini" style="display: flex;flex-wrap: wrap;">
			  		<el-form-item label="账户名" prop="username">
			  			<el-input v-model="addForm.username"></el-input>
			  		</el-form-item>
			  		<el-form-item label="登录密码" prop="password">
			  			<el-input v-model="addForm.password" show-password @input="PwdRules" :disabled="PWDdisabled"></el-input>
						<!-- <div class="steps">
							<el-steps :space="200" :active="stepsActive" process-status="success" :finish-status="finishStatus">
							  <el-step title="弱"></el-step>
							  <el-step title="中"></el-step>
							  <el-step title="强"></el-step>
							</el-steps>
						</div> -->
			  		</el-form-item>
			  		<el-form-item label="角色Id" prop="roleId">
			  			<el-select style="width: 178px;" v-model="addForm.roleId" placeholder="请选择" multiple @focus="chooserole">
			  			    <el-option v-for="item in roleoptions" :key="item.label" :label="item.label" :value="item.id"></el-option>
			  			</el-select>
			  		</el-form-item>
					<el-form-item label="员工姓名" prop="staffName">
					  <el-select 
					    v-model="addForm.staffName" 
					    placeholder="请选择" 
					    @focus="chooseStaff" 
					    @change="choosedRole"
						filterable
					    popper-class="fixed-header-select"
					  >
					    <!-- 选项组 -->
					    <el-group>
					      <!-- 固定头部 -->
					      <div class="select-header" slot="header" 
						  style="font-size: 12px;font-weight: bold;display: flex;justify-content: space-around;padding: 12px;background-color: #f1f1f1;
						  position: sticky;top:0;z-index: 10;">
					        <span>编码</span>
					        <span>姓名</span>
					        <span>科室部门</span>
					      </div>
					      
					      <!-- 选项内容 -->
					      <el-option 
					        v-for="item in Useroptions" 
					        :key="item.id" 
					        :label="item.label" 
					        :value="item.id"
					        class="select-option"
					      >
					        <div class="option-content">
					          <span style="font-size: 12px;margin-left:8px;">{{ item.userCode }}</span>
					          <span style="font-size: 12px;margin-left:8px;">{{ item.label }}</span>
					          <span style="font-size: 12px;margin-left:8px;">{{ item.deptName }}</span>
					        </div>
					      </el-option>
					    </el-group>
					  </el-select>
					</el-form-item>
					<el-form-item label="员工Id" prop="staffId">
						<el-input v-model="addForm.staffId" :disabled="disabled"></el-input>
					</el-form-item>
			  		<el-form-item label="邮箱" prop="email">
			  			<el-input v-model="addForm.email"></el-input>
			  		</el-form-item>
					<el-form-item label="诊所ID" prop="clinicId">
						<el-select v-model="addForm.clinicId" placeholder="请选择" @focus="chooseclinicId">
						    <el-option v-for="item in clinicIdoptions" :key="item.label" :label="item.label" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
			  		<el-form-item label="状态" prop="status">
			  			<el-switch
			  			  v-model="addForm.status"
			  			  active-value="1"
			  			  active-color="#13ce66"
			  			  inactive-value="0"
			  			  inactive-color="#ff4949">
			  			</el-switch>
			  		</el-form-item>
			  	</el-form>
			  </div>
			  <span slot="footer" class="dialog-footer">
			    <el-button size="mini" type="primary" @click="submitForm">添加</el-button>
			    <el-button size="mini" @click="addModelDialogVisible = false;">取消</el-button>
			  </span>
			</el-dialog>
		</div>
		<!-- 编辑Model -->
		<!-- edit dialog -->
		<div class="editModel">
			<el-dialog
			  title="修改用户"
			  :visible.sync="editModelDialogVisible"
			  width="48%"
			  :before-close="handleClose">
			  <!-- 修改主体 -->
			  <div class="editcontent">
				<el-form ref="editForm" :model="editForm" :rules="rules" label-width="88px" size="mini" style="display: flex;flex-wrap: wrap;">
					<el-form-item label="账户名" prop="userId">
						<el-input v-model="editForm.username"></el-input>
					</el-form-item>
					<el-form-item label="账户Id" prop="userId">
						<el-input v-model="editForm.userId" :disabled='disabled'></el-input>
					</el-form-item>
					<el-form-item label="所属诊所" prop="userId">
						<el-input v-model="editForm.clinicId" :disabled='disabled'></el-input>
					</el-form-item>
					<el-form-item label="员工姓名" prop="username">
						<el-input v-model="editForm.username" :disabled="disabled"></el-input>
					</el-form-item>
					<el-form-item label="员工Id" prop="staffId">
						<el-input v-model="editForm.staffId" :disabled="disabled"></el-input>
					</el-form-item>
					<el-form-item label="邮箱" prop="email">
						<el-input v-model="editForm.email"></el-input>
					</el-form-item>
					<el-form-item label="角色Id" prop="roleId">
						<el-select style="width: 178px;" v-model="editForm.roleId" placeholder="请选择" multiple @focus="chooserole">
							<el-option v-for="item in roleoptions" :key="item.label" :label="item.label" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="用户状态" prop="status">
						<el-switch
						  v-model="editForm.status"
						  active-value="1"
						  active-color="#13ce66"
						  inactive-value="0"
						  inactive-color="#ff4949">
						</el-switch>
					</el-form-item>
				</el-form>
			  </div>
			  <span slot="footer" class="dialog-footer">
				<el-button size="mini" type="primary" @click="editSubmit">确定</el-button>
				<el-button size="mini" @click="editModelDialogVisible = false">取消</el-button>
			  </span>
			</el-dialog>
		</div>
		<!-- 查看dialog -->
		<!-- 详情查看Dialog -->
		<el-dialog
		  title="用户详情"
		  :visible.sync="detailDialogVisible"
		  width="50%"
		  :before-close="handleClose">
		  <el-descriptions :column="2" border>
		    <el-descriptions-item label="账户名">{{ detailData.username }}</el-descriptions-item>
		    <el-descriptions-item label="用户ID">{{ detailData.userId }}</el-descriptions-item>
		    <el-descriptions-item label="状态">
		      <el-tag :type="detailData.status === '1' ? 'success' : 'danger'" size="small">
		        {{ detailData.status === '1' ? '可用' : '锁定' }}
		      </el-tag>
		    </el-descriptions-item>
		    <el-descriptions-item label="手机号">{{ detailData.tel }}</el-descriptions-item>
		    <el-descriptions-item label="邮箱">{{ detailData.email }}</el-descriptions-item>
		    <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
		    <el-descriptions-item label="所属诊所">{{ detailData.clinicName }}</el-descriptions-item>
		    <!-- 可以根据需要添加更多字段 -->
		  </el-descriptions>
		  <span slot="footer" class="dialog-footer">
		    <el-button size="mini" @click="detailDialogVisible = false">关闭</el-button>
		  </span>
		</el-dialog>
		<!-- 重置密码dialog -->
		<div class="resetPwd">
			<el-dialog
			  title="重置密码"
			  :visible.sync="resetPwddialogVisible"
			  width="20%"
			  :before-close="handleClose">
				<div v-if="this.Self === true" style="padding: 12px;text-align: center;">
					<span>当前用户：<i class="el-icon-aim"></i>{{ userName + '（我）' }}</span>
				</div>
				<div v-else style="padding: 12px;text-align: center;">
					<span>当前用户：{{ userName }}</span>
				</div>
			  <el-form ref="resetPwdForm" :model="resetPwdForm" :rules="rules" label-width="88px" size="mini" style="display: flex;flex-wrap: wrap;">
					<el-form-item label="原始密码" prop="userId">
						<el-input show-password v-model="resetPwdForm.oldPassword"></el-input>
					</el-form-item>
					<el-form-item label="新密码" prop="userId">
						<el-input show-password v-model="resetPwdForm.newPassword"></el-input>
					</el-form-item>
				</el-form>
			  <span slot="footer" class="dialog-footer">
				<el-button size="mini" @click="xtRest">系统重置</el-button>
			    <el-button size="mini" @click="resetPwddialogVisible = false">取 消</el-button>
			    <el-button size="mini" type="primary" @click="resetPwdSubmit">确 定</el-button>
			  </span>
			</el-dialog>
		</div>
		<!-- 用户查询 -->
		<el-dialog
		    title="用户查询"
		    :visible.sync="searchDialogVisible"
		    width="50%"
			top="18px"
		    :before-close="handleClose">
		    
		    <el-form :model="userForm" label-width="120px" label-position="left">
		      <div style="display: flex;">
		        <!-- 左侧表单区域 -->
		        <div style="flex: 1; padding-right: 20px;font-size: 12px;">
		          <el-form-item label="用户编码">
		            <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
		          </el-form-item>
		          
		          <el-form-item label="用户昵称">
		            <el-input 
		              v-model="userForm.staffName" 
		              placeholder="用户昵称"></el-input>
		          </el-form-item>
		          
				  <el-form-item label="UID">
				    <el-input v-model="userForm.uid" disabled></el-input>
				  </el-form-item>
				  
		          <el-form-item label="用户角色UID">
		            <el-input 
		              v-model="userForm.staffId" >
					  </el-input>
		          </el-form-item>
		          
		          <el-form-item label="国家">
		            <el-select v-model="userForm.country" placeholder="请选择">
		              <el-option label="中国" value="CN"></el-option>
		            </el-select>
		          </el-form-item>
		          
		          <el-form-item label="手机(选填)">
		            <el-input v-model="userForm.phone"></el-input>
		          </el-form-item>
		          
		          <el-form-item label="Email(选填)">
		            <el-input v-model="userForm.email"></el-input>
		          </el-form-item>
		          
		          
		          
		          <el-checkbox disabled v-model="userForm.mustChangePassword">用户首次登录必须更改密码</el-checkbox>
		          <el-checkbox disabled v-model="userForm.sendNotification">发送一封通知邮件给新增用户(编辑信息)</el-checkbox>
		        </div>
		        
		        <!-- 右侧权限区域 -->
		        <div style="flex: 1; border-left: 1px solid #eee; padding-left: 20px;">
		          <el-form-item label="用户诊所ID">
		            <el-tag>{{ this.clinicId }}</el-tag>
			<!-- 		<template slot-scope="{ row }">
						<el-tag>{{ docclinicMap[this.clinicId] || '' }}</el-tag>
					</template> -->
		          </el-form-item>
		          
		          <el-form-item label="共享文件夹权限">
		            <div>
		              <div>用户权限</div>
		              <div>读取/写入: Multimedia, 照片</div>
		            </div>
		          </el-form-item>
		          
		          <!-- <el-form-item label="编辑应用程序权限">
		            <div>允许使用所有的应用程序</div>
		            <el-button type="text" icon="el-icon-edit">编辑</el-button>
		          </el-form-item> -->
		        </div>
		      </div>
		    </el-form>
		    
		    <span slot="footer" class="dialog-footer">
		      <el-button size="mini" @click="searchDialogVisible = false">关  闭</el-button>
		      <!-- <el-button type="primary" @click="handleCreate">创 建</el-button> -->
		    </span>
		  </el-dialog>
		  
	</div>
</template>

<script>
	// selfs / sons
	// // 接口
	import { 
		getAllUser,roleList,GetUserInfo,
		addUser,updateUser,getuserInfo,editPwd
	} from "@/api/user.js";
	import { selectList,yglist } from "@/api/staff/staff.js"; // 获取员工信息
	import { doccliniclist } from "@/api/cinic/cinic.js"; // 获取员工信息
	import { docclinic } from "@/api/cinic/cinic.js";
	export default {
		inject: ['reload'], // 无痕刷新
		components: {
			
		},
		data() {
			return {
				userName:'',
				nameTitle:'系统用户管理',
				filterText:'',
				searchValue: '',
				searchTreeValue:'',
				selectValue: '',
				windowWidth: '',
				loading: false,
				Self: false,
				disabled: true,
				PWDdisabled: true,
				detailDialogVisible: false, // 查看
				searchDialogVisible:false,
				detailData: {}, // 存储详情数据
				addModelDialogVisible: false,
				editModelDialogVisible: false,
				resetPwddialogVisible: false,
				tableWidth: '',
				stepsStatus:'', //步骤条状态
				finishStatus:'',
				clinicId:'',
				stepsActive:0, //步骤条激活
				pageNum: 1, //当前页currentPage
				pageSize: 15,
				totalSize: 10, //总条数
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				userForm: {
				        username: '九阵666',
						staffName:'',
				        password: '',
				        confirmPassword: '',
				        country: 'CN',
				        phone: '',
				        email: '',
				        uid: '',
				        mustChangePassword: true,
				        sendNotification: false
				      },
				elTree:[{ label: '宜宾九阵软件科技有限公司', path:'', title:'', icon:'el-icon-news',
					children:[
						{
							label: '运维部',
							path:'',
							title:'',
							icon:'el-icon-news',
							children:[
								{
									label: '运维一组',
									path:'',
									title:'',
									icon:'el-icon-news',
								},
								{
									label: '运维二组',
									path:'',
									title:'',
									icon:'el-icon-news',
								},
								{
									label: '运维三组',
									path:'',
									title:'',
									icon:'el-icon-news',
								},
							]
						},
						{
							label: '后勤部',
							path:'',
							title:'',
							icon:'el-icon-news',
							children:[
								{
									label: '后勤一部',
									path:'',
									title:'',
									icon:'el-icon-news',
								},
								{
									label: '后勤二部',
									path:'',
									title:'',
									icon:'el-icon-news',
								}
							]
						},
						{
							label: '财务部',
							path:'',
							title:'',
							icon:'el-icon-news',
							children:[
								{
									label: '宜宾一部',
									path:'',
									title:'',
									icon:'el-icon-news',
								},
								{
									label: '成都二部',
									path:'',
									title:'',
									icon:'el-icon-news',
								},
								{
									label: '水富三部',
									path:'',
									title:'',
									icon:'el-icon-news',
								}
							]
						},
						{
							label: '研发部',
							path:'',
							title:'',
							icon:'el-icon-news',
							children:[
								{
									label: '后端',
									path:'',
									title:'',
									icon:'el-icon-news',
									children:[
										{
											label: '后端一组',
											path:'',
											title:'',
											icon:'el-icon-news',
										},
										{
											label: '后端二组',
											path:'',
											title:'',
											icon:'el-icon-news',
										}
									]
								},
								{
									label: '前端',
									path:'',
									title:'',
									icon:'el-icon-news',
									children:[
										{
											label: '前端一组',
											path:'',
											title:'',
											icon:'el-icon-news',
										},
										{
											label: '前端二组',
											path:'',
											title:'',
											icon:'el-icon-news',
										}
									]
								},
								{
									label: '设计',
									path:'',
									title:'',
									icon:'el-icon-news',
									children:[
										{
											label: 'UI一部',
											path:'',
											title:'',
											icon:'el-icon-news',
										},
										{
											label: '平面二部',
											path:'',
											title:'',
											icon:'el-icon-news',
										}
									]
								},
							]
						}
					] ,
				}],
				Useroptions:[], //员工档案选择
				roleoptions:[], //角色信息选择
				clinicIdoptions:[], //诊所id选择
				docclinicOptions:[], // 获取诊所列表
				options: [{value: '1',label: '可用'},{value: '0',label: '锁定'}],
				// header查询重置按钮
				// feetBtn:[{ refesh:"refesh", label:"查看", types:"primary", icon:"el-icon-sort" },{ title:"导入", icon:"el-icon-upload2" }],
				// 页面默认按钮// 基础按钮配置（始终显示）
				defaultButtons:[
					// { title:"新增西成药",icon:"el-icon-adds", type:"primary" },
					// { title:"修改西成药",icon:"el-icon-edit", type:"primary" },
					{ title:"查看",icon:"el-icon-watch", type:"primary" },
					// { title:"删除",icon:"el-icon-del", type:"danger" },
					// { title:"目录引用",icon:"el-icon-closeFiles", type:"primary" },
					{ title:"打印",icon:"el-icon-ggml", type:"primary" },
					{ title:"导出",icon:"el-icon-export", type:"primary" },
					{ title:"关闭",icon:"el-icon-close", type:"primary" },
				],
				// 最终使用的按钮数组
				// feetBtn: [],
				feetBtn:[
				 // { refesh:"refesh", title:"新增", type:"primary", icon:"el-icon-edit" },
				 // { refesh:"refesh", label:"修改", types:"primary", icon:"el-icon-finished" },
				 // { refesh:"refesh", label:"删除", types:"primary", icon:"el-icon-document-checked" },
				 { label:"导入", icon:"el-icon-upload2" },
				 { label:"关闭", types:"primary", icon:"el-icon-close" },
				 ],
				headerBtn:[{ title:"重置", icon:"el-icon-refresh" }],
				headerBtnbottomRight:[{ title:"导出", icon:"el-icon-download" },{ icon:"el-icon-refresh" },{ icon:"el-icon-s-tools" },{ icon:"el-icon-full-screen" }],
				// 表格行
				tableRows:[
					{ name:"账户名", prop:"username", type:"" },{ name:"当前系统", prop:"clinicName", type:"" },
					{ name:"用户ID", prop:"userId", type:"" },{ name:"手机号", prop:"tel", type:"" },
					{ name:"邮箱", prop:"email", nz:"nz" },{ name:"创建时间", prop:"createTime", type:"" },
				],
				// 表格data
				tableData:[],
				docclinicMap:{},
				restaurants:[],
				// add
				addForm:{
					username:'', 
					status: '1',
					roleId:[], 
					clinicId:'',// 诊所ID
					staffName:'',
					staffId: '',
					password:'123456',
					email:'', 
				},
				// edit
				editForm:{
					username:'',
					userId:0,
					email:'',
					roleId:[],
					status:'',
					clinicId:0,
				},
				resetPwdForm:{
					userId:0,
					oldPassword:'', 
					newPassword: '',
				},
				//验证规则 pattern: /^[a-zA-Z]+$/,
				rules:{
				    username: [
				      { required: true, message: "请输入账户名", trigger: "blur" },
				      { min: 2, max: 8, message: "长度在2到8个字符", trigger: "blur" },
					  { min:2, max: 8,   message: '长度在2到8个字符', trigger: 'blur' }
				    ],
				      //密码
				    password:[
						{ required: true, message: "请输入密码", trigger: "blur" },
						{ min: 6, max: 12, message: "当前密码安全性低！", trigger: "blur" },
				    ],
				      //邮箱
				    // email:[
				    //    { required: true, pattern:/^\w{3,12}@\w{1,5}\.[a-z]{2,3}$/,required: true, message: "邮箱格式不正确！", trigger: "blur" },
				    // ]
				}
			}
		},
		mounted() {
			//获取数据源
			this.loadData();
			this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
			this.userName = this.userInfo.username;
			// this.clinicId = this.userInfo.clinicId;
			// console.log(clinicId,'clinicIdclinicId');
			//获取动态盒子宽度，实时赋值给右侧 => this.$refs.mainRight.offsetWidth;
			this.$nextTick(()=>{
				this.updateWindowWidth();
				window.addEventListener('resize', this.updateWindowWidth);
			})
			this.initButtons(); // 引入全局自定义封装方法
		},
		watch: {
		  filterText(val) {
			this.$refs.tree.filter(val);
		  }
		},
		methods:{
			initButtons() {
			    // 获取当前路由路径
			    const currentPath = this.$route.path;
			    // 获取路由对应的权限按钮
			    const routeButtons = this.$getRouteButtons(currentPath);
			    // console.log(routeButtons,'routeButtonsrouteButtons');
			    // 合并到现有按钮数组
			    this.feetBtn = this.$mergeButtons(this.defaultButtons, routeButtons);
				// console.log(this.feetBtn,'this.feetBtnthis.feetBtn');
			},
			/*
				数据源
			*/
			async loadData(){
				let res = await getAllUser({
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					userName: this.searchValue
				});
				if(res.code === 200){
					this.tableData = res.data.content;
					this.totalSize = res.data.totalSize
					// 搜索建议
					this.restaurants = this.tableData.map(item =>{
						return { value:item.username , ...item }
					})
					
				};
			},
			// 搜索建议
			querySearch(queryString, cb) {
				var restaurants = this.restaurants;
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				// 调用 callback 返回建议列表的数据
				cb(results);
			},
			async getcilinc(){
				// 所有菜单
				let res = await docclinic();
				this.docclinicOptions = res.data.map(v=>{ return { label: v.name , ...v }});
				// 将 民族 转换为 minZuMap 格式
				this.docclinicMap = this.docclinicOptions.reduce((map, item) => {
					map[item.id] = item.label;  // 使用 id 作为键，label 作为值
					return map;
				}, { 1: '数据不对，默认null' });  // 保留初始值
			},
			createFilter(queryString) {
				return (restaurant) => {
				  return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
				};
			},
			// 在methods中添加
			async handleUserSearch() {
			  if (!this.currentTable || !this.currentTable.userId) {
			    this.$message({ type: 'warning', message: '请先选择一条用户数据' });
			    return;
			  }
			  
			  try {
			    this.loading = true;
			    const res = await GetUserInfo({ userid: this.currentTable.userId });
			    if (res.code === 200) {
			      // 将返回数据填充到userForm中
			      this.userForm = {
			        username: res.data.username || '',
			        staffName: res.data.staffName,
			        staffId: res.data.staffId,
			        country: res.data.country || 'CN',
			        phone: res.data.phone || '',
			        email: res.data.email || '',
			        uid: res.data.userId || '',
					clinicId: res.data.clinicId,
			        mustChangePassword: res.data.mustChangePassword || false,
			        sendNotification: false
			      };
			      this.searchDialogVisible = true;
				  this.editForm.clinicId = res.data.clinicId
			    } else {
			      this.$message.error(res.message || '获取用户信息失败');
			    }
			  } catch (error) {
			    console.error('获取用户信息失败:', error);
			    this.$message.error('获取用户信息失败');
			  } finally {
			    this.loading = false;
			  }
			},
			handleSelect(item) {
				this.loading = true;
				setTimeout(() =>{
					this.tableData = [];
					this.tableData.push(item)
					this.loading = false
				},1500)    
			},
			// 表格单选
			handleCurrentTableChange(val){
				this.currentTable = val;
				this.$notify({
				  title: '成功',
				  message: this.currentTable.username + '已选择',
				  type: 'success'
				});
			},
		    // 触发员工信息选择
		    async chooseStaff(){
			   // 员工信息数据源
			  let res = await yglist()
				this.Useroptions = res.data
				this.Useroptions = this.Useroptions.map(v=>{
					return { label:v.fullName , ...v }
				});
				// console.log(this.Useroptions,'kkkkkkksjj');
			},
			// 触发角色信息选择
			async chooserole(){
			  // 角色信息数据源
				this.clinicId = this.editForm.clinicId;
				console.log(this.clinicId,'this.clinicIdthis.clinicIdthis.clinicId');
				this.roleoptions = await roleList({
				   clinicId:this.clinicId,
				   pageNum: this.pageNum,
				   pageSize: this.pageSize
				})
				this.roleoptions = this.roleoptions.map(v=>{
					return { label:v.roleName , ...v }
				})
			},
			// 触发诊所id选择
			async chooseclinicId(){
			  // 角色信息数据源
				this.clinicIdoptions = await doccliniclist()
				this.clinicIdoptions = this.clinicIdoptions.data.map(v=>{
					return { label:v.name , ...v }
				})
			},
			// 显示详情方法
			showDetail(row) {
			  this.detailData = { ...row }; // 复制行数据到详情数据
			  this.detailDialogVisible = true; // 打开对话框
			},
			// 表格底部循环按钮事件
			async feetHandClick(v){
				// i event
				// 处理逻辑 => 新增
				if(v.title == '用户新增' || v.title.includes('新增')){
					// 处理索引2的逻辑 => 新增
					this.addModelDialogVisible = true
				}
				// 处理逻辑 => 修改
				else if (v.title === '修改用户' || v.title.includes('修改')){
					// 处理索引1的逻辑 => 修改
					if(this.currentTable.length != 0){
						this.chooserole();
						// 处理索引0的逻辑 ==> 修改
						this.editModelDialogVisible = true;
						// this.editForm = {...row}; // 启用
						//  查询用户信息
						let res = await getuserInfo({ userid:this.currentTable.userId })
						this.editForm = {...res.data}
					}else{
						this.$message({ type: 'warning', message: '请先选择一条数据'});
					}
				}
				// 处理逻辑 => 删除
				else if(v.title === '删除' || v.title.includes('删除')){
					// 处理索引2的逻辑 => 删除
					this.$message({ type: 'success', message: '系统用户不能被删除!'})
				}
				// 修改feetHandClick方法中的查询逻辑
				else if(v.title === '查询' || v.title.includes('查询')){
				  this.handleUserSearch();
				}
				// 处理逻辑 => 查看
				else if(v.title === '查看' || v.title.includes('查看')){
					if(this.currentTable){
						this.detailData = { ...this.currentTable }; // 复制行数据到详情数据
						this.detailDialogVisible = true; // 打开对话框
					}else{
						this.$message({ type: 'warning', message: '请先选择一条数据'});
					}
				}
				// 处理逻辑 => 导入
				else if(v.title === '导入' || v.title.includes('导入')){
					this.$confirm('敬请期待')
					.then(_ => {})
					.catch(_ => {});
				}
				// 处理逻辑 => 查询
				else if(v.title === '查询' || v.title.includes('查询')){
					if(this.currentTable){
						this.detailData = { ...this.currentTable }; // 复制行数据到详情数据
						this.detailDialogVisible = true; // 打开对话框
					}else{
						this.$message({ type: 'warning', message: '请先选择一条数据'});
					}
				}
				// 处理逻辑 => 修改密码
				else if (v.title === '修改密码' || v.title.includes('修改密码')){
					// 处理索引1的逻辑 => 修改
					if(this.currentTable){
						this.resetPwddialogVisible = true;
					}else{
						this.$message({ type: 'warning', message: '请先选择一条数据'});
					}
				}
				// 处理逻辑 => 导出
				else if(v.title === '打印' || v.title.includes('打印')){
					this.handlePrint();
				}
				// 处理逻辑 => 关闭
				else if(v.title === '关闭' || v.title.includes('关闭')){
					setTimeout(() =>{
						window.history.back();
					},888)
				}
				// 处理逻辑
				else{
					this.$message({ type: 'error', message: '操作失败,请联系管理员！'})
				}
			},
			// 取消新增重置
			resetForm(){
				this.$refs.addForm.resetFields();
				this.addModelDialogVisible = false;
				// this.editModelDialogVisible = false;
			},
			//  确认新增
			async submitForm(){
			//触发验证表单
			  this.$refs.addForm.validate(async(valid) => {
				if(valid){
				//验证通过
				// console.log(this.addForm);
				let rs = await addUser(this.addForm)
				if (rs.code === 200){
					this.$message({ message:rs.message, type:"success"});
					// 更新数据驱动
					this.reload();
					this.addModelDialogVisible = false;
				}else{
					//验证失败
					this.$message({ type: "info", message: rs.message });
				}
			  }
			  });
			},
			// 打印按钮点击事件
			handlePrint() {
			  this.$confirm('请选择打印方式', '打印设置', {
			    confirmButtonText: 'Lodop打印',
			    cancelButtonText: '浏览器打印',
			    type: 'warning'
			  }).then(() => {
			    // 用户选择Lodop打印
				console.log('用户选择Lodop打印');
			    this.printWithLodop();
			  }).catch(() => {
			    // 用户选择浏览器打印
			    // this.printWithBrowser()
				console.log('用户选择浏览器打印');
				this.$message({ type: 'warning', message: '浏览器打印出错,正在跳转lodop打印！'});
				this.loading = true;
				setTimeout(() =>{
					this.printWithLodop();
					this.loading = false;
				},1888)
			  })
			},
			// 系统重置密码
			xtRest(){
				this.$confirm("执行此操作系统将重置到最初始的系统密码, 是否确认继续?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
				})
				.then(async() => {
					this.resetPwdForm ={
						newPassword:'123456',
						userId:this.userId
					}
					let res = await editPwd(this.resetPwdForm);
					if (res.code === 200) {
						// 条件判断
						if(this.Self === true){
							//清除本地存储，回退重新登录
							this.$message({ type:"success",message:'当前账户的密码已修改，请重新登录！' })
							localStorage.clear();
							this.$router.push('/login');
						}else{
							this.$message({ type: 'success', message: '密码已重置！'});
							//更新数据源
							this.loadData();
							this.resetPwddialogVisible = false;
						}
					} else {
						this.$message.error(res.message)
					}
				})
				.catch(() => {
					this.$message({ type: "info", message: "已取消"});
				});
				this.resetPwdForm.oldPassword = '123456'
				this.resetPwdForm.newPassword = ''
			},
			// 使用Lodop打印并设计
			printWithLodop() {
				  // 准备表格数据
				  const tableData = this.tableData.map(item => {
				    return {
				      ...item,
				      // 添加任何需要转换的字段
				    };
				  });
				  
				  // 准备当前选中行数据
				  const currentTable = this.currentTable;
				  
				  this.$router.push({
				    path: '/PrintTemplateDesigner',
				    query: {
				      tableData: JSON.stringify(tableData),
				      currentTable: JSON.stringify(tableData),
				      templateName: this.nameTitle
				    }
				});
			},
			// 状态切换方法
			async toggleStatus(row) {
				// console.log(row,'ooooooppp');
				//  查询用户信息
				let res = await getuserInfo({ userid:row.userId })
				this.editForm = {...res.data}
			  try {
			    const newStatus = row.status === '1' ? '0' : '1';
				this.editForm.status = row.status
			    const res = await updateUser(this.editForm);
				if (res.code === 200) {
				  row.status = newStatus; // 更新本地状态
				  this.$message({
					type: 'success',
					message: `状态已${newStatus === '1' ? '启用' : '禁用'}`
				  });
				  this.loading = false;
				} else {
				  this.$message.error(res.message || '状态更新失败');
				  this.loading = false;
				} 
			  } catch (error) {
			    console.error('状态更新失败:', error);
			    this.$message.error('状态更新失败');
			  } finally {
			    this.loading = false;
			  }
			},
			// 状态改变
			ChangeStatus(val){
				// console.log(val);
			},
			//删除
			// handleDelete(id) {
			// 	this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
			// 	confirmButtonText: "确定",
			// 	cancelButtonText: "取消",
			// 	type: "warning",
			// 	})
			// 	.then(() => {
			// 		this.$message({ type: "info", message: "暂不支持,请联系工作人员!"});
			// 	})
			// 	.catch(() => {
			// 		this.$message({ type: "info", message: "已取消"});
			// 	});
			// },
			// 表格编辑栏
			async handleClickEdit(row) {
				this.chooserole();
			 // 处理索引0的逻辑 ==> 修改
				this.editModelDialogVisible = true;
				// this.editForm = {...row}; // 启用
				//  查询用户信息
				let res = await getuserInfo({ userid:row.userId })
				this.editForm = {...res.data};
				console.log(this.editForm,'查询用户信息查询用户信息');
			},
			// 提交编辑
			async editSubmit(){
				// 重新定义一个新对象 ， 否则拿不到参数报错 => 100003 参数获取失败 ，多空格和中文逗号导致
				let oo = {
					email: "",
					roleId: [],
					clinicId:0,
					status: "",
					userId: 0,
					username: ""
				}
				oo = this.editForm
				let res = await updateUser(oo)
				if (res.code === 200) {
					this.$message({ type: 'success', message: res.message });
					//更新数据源
					this.loadData();
					this.editModelDialogVisible = false;
				} else {
					this.$message.error(res.message)
				}
			},
			// 重置密码
			HandleCommand(command,row) {
				if(command){
					// this.$router.push('/profile');
					this.resetPwddialogVisible = true;
				}else{
					this.$message({ type: 'danger', message: '系统错误,请联系管理员!'});
				}
			},
			// 提交重置密码
			async resetPwdSubmit(){
				let res = await editPwd(this.resetPwdForm);
				if (res.code === 200) {
					// 条件判断
					if(this.Self === true){
						//清除本地存储，回退重新登录
						this.$message({ type:"success",message:'当前账户的密码已修改，请重新登录！' })
						localStorage.clear();
						this.$router.push('/login');
					}else{
						this.$message({ type: 'success', message: '密码已重置！'});
						//更新数据源
						this.loadData();
						this.resetPwddialogVisible = false;
					}
				} else {
					this.$message.error(res.message)
				}
			},
			/*
				about tree
			*/
			handleNodeClick(data,e) {
				this.CatalogueName = data.title
				this.iconComes = 'el-icon-' + this.makePy(data.label)
				// this.loadData();
			},
			PwdRules(val){

			},
			// 选择员工赋值id
			choosedRole(val){
				// console.log(val);
				this.addForm.staffId = val
				let vrs = this.Useroptions.find(v => v.id === val)
				this.addForm.staffName = vrs.fullName
			},
			// 过滤器
			filterNode(value, data) {
				if (!value) return true;
				return data.label.indexOf(value) !== -1;
			},
			handleClose(done) {
				this.formdisabled = true;
				done();
			},
			// 步骤
			handClick(i) {
				// i event
				switch (i) {
					case 0:
						// 处理索引0的逻辑 页面刷新
						this.loading = true;
						setTimeout(() => {
							this.searchValue = '';
							this.searchTreeValue = '';
							this.selectValue = ''; 
							this.$message({type:'success',message:'已重置'})
							this.loading = false;		
						}, 800)
						break;
				}
			},
			headerBtnbottomRightClick(i){
				// i event
				switch (i) {
					case 0:
						// 处理索引0的逻辑  => 导出
						this.$message({ type: "info", message: "暂不支持,请联系工作人员!"});
						break;
					case 1:
						// 处理索引0的逻辑 页面刷新
						this.loading = true;
						setTimeout(() => {
							this.reload();
							this.$message({type:'success',message:'已重置'})
							this.loading = false;		
						}, 1500)
						break;
				}
			},
			// col 里面包含了表头字段和名称，list 是表格数据
			columnWidth(col, list) {
			  let prop = col.prop,lab = col.lab;
			  let width = 40; // 设定一个最小值
			  let maxlenStr = ""; // 最长字符串
			  for (let info of list) {
				if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
			  }
			  width = Math.max(width, len(lab), len(maxlenStr));
			  // 表格自带的内边距(20px) 自调
			  return width + 12; // 这里加了 12px
			  function len(str) {
				// 实际分配长度可根据需要自行调整
				let length = 8;
				for (const char of str + "") {
				  // 英文小写字符 8px
				  if ("a" <= char && char <= "z") length += 12;
				  // 英文大写字符 8px
				  else if ("A" <= char && char <= "Z") length += 8;
				  // 数字
				  else if (Number.isFinite(Number(char))) length += 8;
				  // 中文字符 28px
				  else if (char >= "\u4e00" && char <= "\u9fa5") length += 18;
				  // 其他 8px
				  else length += 12;
				}
				return length;
			  }
			},
			// db events
			handledbRow(row, column, event){
				// console.log(row);
			},
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageSize = val;
				this.pageNum = 1; // 重置为第一页
				this.loadData();
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
				this.loadData();
			},
			// 实时宽度
			updateWindowWidth() {
			    this.windowWidth = window.innerWidth - 368;
			},
		},
	}
</script>

<style lang="less" scoped>
	// 穿透
	/deep/ .el-select-dropdown__list {
		max-height: 300px;
		overflow-y: auto;
		margin-top: -6px;
	}
	/deep/ .el-dialog__header{
		padding: 12px;
		background-color: #007bb0;
	}
	/deep/ .el-dialog__body{
		margin-top: -20px;
	}
	/deep/ .el-dialog__title{
		font-size: 12px;
		color: #fff;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close{
		color: #fff;
	}
	/deep/ .el-dropdown{
		font-size: 12px;
		cursor: pointer;
	}
	/deep/ .el-dropdown-link {
		cursor: pointer;
		color: #409EFF;
	}
	/deep/ .demonstration {
		display: block;
		color: #8492a6;
		font-size: 14px;
		margin-bottom: 20px;
	}
	.user{
		width: 100%;
		height: 100%;
		background-color: #fff;
		padding: 4px;
		.title{
			height: 40px;
			line-height: 40px;
			span{
				font-weight: 300;
				margin-left: 12px;
			}
		}
		
		.main{
			width: 100%;
			margin-top: 8px;
			display: flex;
			.main-left{
				flex: 1;
				// background-color: salmon;
				.tree{
					margin-top: 8px;
				}
				  /* 树形结构节点添加连线 */
				/deep/  .tree .el-tree-node {
				    position: relative;
				    // padding-left: 16px;
				  }
				
				/deep/  .tree .el-tree-node :last-child:before {
				    height: 38px;
				  }
				
				/deep/  .tree .el-tree > .el-tree-node:before {
				    border-left: none;
				  }
				  .tree-container .el-tree > .el-tree-node:after {
				    border-top: none;
				  }
				
				/deep/  .tree .el-tree-node__children .el-tree-node:before {
				    content: '';
				    left: 12px;
				    position: absolute;
				    right: auto;
				    border-width: 1px;
				  }
				/deep/  .tree .el-tree-node__children {
					padding-left: 0px;
				  }
				/deep/  .tree .el-tree-node:after {
				    content: '';
				    left: 12px;
				    position: absolute;
				    right: auto;
				    border-width: 1px;
				  }
				/deep/  .tree .el-tree-node__expand-icon.is-leaf {
				    display: none;
				  }
				
				 /deep/ .tree .el-tree-node:before {
				    border-left: 1px dashed #dddddd;
				    bottom: 0px;
				    height: 100%;
				    top: -26px;
				    width: 1px;
				  }
				
				/deep/  .tree .el-tree-node:after {
				    border-top: 1px dashed #dddddd;
				    height: 20px;
				    top: 12px;
				    width: 24px;
				  }
			}
			.main-right{
				flex: 6;
				margin-left: 12px;
				.searchValue{
					display: flex;
					/deep/ .el-input{
						width: 188px;
					}
					/deep/ .el-select{
						margin-left: 8px;
					}
					/deep/ .el-button{
						margin-left: 8px;
					}
				}
				.btnBottom{
					display: flex;
					justify-content: space-between;
					margin-top: 18px;
				}
				.content{
					display: flex;
					justify-content: center;
					width: 100%;
					margin-top: 12px;
					border: 1px solid #dddddd;
					border-radius: 4px;
					/deep/ .el-table .cell{
						font-size: 12px;
						// text-align: center;
						text-overflow: ellipsis;
						white-space: nowrap;
						overflow: hidden;
					}
					/deep/ .el-table {
					    width: 100%;
					    
					}
					/deep/ td {
						padding: 0!important;
						height: 32px;
					}
					/deep/ .el-table td.el-table__cell div :first-child{
						text-align: center;
					}
					
				}
			}
			
		}
		.addModel{
			
		}
	}
</style>